<template>
  <div class="form-container">
    <!-- 添加填入示例按钮 -->
    <div class="form-header">
      <el-button type="primary" size="small" @click="fillExamples" class="fill-examples-btn">
        <el-icon>
          <DocumentCopy />
        </el-icon>
        填入示例
      </el-button>
    </div>
    <el-form :model="formData" :inline="true" label-position="top" :validate-on-rule-change="false" ref="formRef"
      class="compact-form">
      <el-form-item v-for="(field, index) in formFields" :key="index" :label="field.name"
        :prop="`${field.prop || field.name}`"
        :error="formSubmitted && !isFieldValid(field) ? getErrorMessage(field) : ''">
        <!-- 文本输入 -->
        <el-input v-if="field.type === 'text'" v-model="field.value" :placeholder="field.placeholder" />

        <!-- 多行文本输入 -->
        <el-input v-else-if="field.type === 'textarea'" v-model="field.value" type="textarea" :rows="4"
          :placeholder="field.placeholder" />

        <!-- 日期选择器 -->
        <el-date-picker v-else-if="field.type === 'date'" v-model="field.value" type="date"
          :placeholder="field.placeholder" style="width: 100%" />

        <!-- 单选框 -->
        <el-radio-group v-else-if="field.type === 'radio'" v-model="field.value">
          <el-radio v-for="(option, optIndex) in field.options" :key="optIndex" :label="option">
            {{ option }}
          </el-radio>
        </el-radio-group>

        <!-- 颜色选择器 -->
        <div v-else-if="field.type === 'color'" class="color-field">
          <el-color-picker v-model="field.value" show-alpha />
          <span class="color-value">{{ field.value || field.placeholder }}</span>
        </div>

        <!-- 滑块 -->
        <el-slider v-else-if="field.type === 'range'" v-model="field.value" :min="field.min" :max="field.max"
          :step="field.step" :show-input="true" />

        <!-- 复选框 -->
        <el-checkbox-group v-else-if="field.type === 'checkbox'" v-model="field.value">
          <el-checkbox v-for="(option, optIndex) in field.options" :key="optIndex" :label="option">
            {{ option }}
          </el-checkbox>
        </el-checkbox-group>

        <!-- 文件上传 -->
        <div v-else-if="field.type === 'file'" class="file-upload-wrapper">
          <!-- 上传按钮区域 -->
          <div class="upload-buttons" v-if="!field.fileUrl">
            <el-upload class="upload-field" :action="uploadUrl" :auto-upload="true" :accept="field.accept"
              :on-change="(file) => handleFileChange(file, field)"
              :before-upload="(file) => beforeFileUpload(file, field)"
              :on-success="(response, file) => handleFileSuccess(response, file, field)" :limit="1"
              :headers="uploadHeaders" :data="uploadData">
              <el-button type="primary">上传文件 {{ field.accept || '' }}</el-button>
            </el-upload>

            <el-button type="primary" @click="toggleUrlInput(field)" class="url-button">
              输入链接
            </el-button>
          </div>

          <!-- URL输入框区域 -->
          <div class="url-input-section" v-if="field.showUrlInput && !field.fileUrl">
            <el-input v-model="field.urlInput" placeholder="请输入文件URL" size="small"
              @keyup.enter="confirmUrlInput(field)">
              <template #append>
                <el-button @click="confirmUrlInput(field)">确认</el-button>
              </template>
            </el-input>
          </div>

          <!-- 文件预览区域 -->
          <div v-if="field.fileUrl" class="file-preview">
            <!-- 如果是图片，显示图片预览 -->
            <div class="image-preview-container" v-if="isImageFile(field.fileName)">
              <div class="delete-button" @click="removeFile(field)">
                <el-icon>
                  <Close />
                </el-icon>
              </div>
              <div class="image-preview">
                <img :src="field.fileUrl" alt="预览图片" />
              </div>
              <div class="file-name">{{ field.fileName }}</div>
            </div>

            <!-- 非图片文件显示 -->
            <div class="file-info" v-else>
              <div class="file-name">{{ field.fileName }}</div>
              <div class="file-url">{{ field.fileUrl }}</div>
              <el-button size="small" type="danger" @click="removeFile(field)">删除文件</el-button>
            </div>
          </div>

          <div class="el-upload__tip">{{ field.placeholder }}</div>
        </div>

        <!-- 语音输入 -->
        <div v-else-if="field.type === 'voice'" class="voice-field">
          <el-button :type="isRecording && currentRecordingField === field ? 'danger' : 'primary'"
            @click="toggleVoiceRecording(field)"
            :icon="isRecording && currentRecordingField === field ? 'el-icon-video-pause' : 'el-icon-microphone'">
            {{ isRecording && currentRecordingField === field ?
              `录音中 (${recordingTime}s)` : '开始录音' }}
          </el-button>
          <div v-if="field.recordingUrl" class="voice-preview">
            <audio controls :src="field.recordingUrl"></audio>
          </div>
          <div class="el-upload__tip">{{ field.placeholder }}</div>
        </div>

        <!-- 选择器 -->
        <el-select v-else-if="field.type === 'selector'" v-model="field.value" :placeholder="field.placeholder"
          style="width: 100%">
          <el-option v-for="(option, optIndex) in field.options" :key="optIndex"
            :label="typeof option === 'object' ? option.label : option"
            :value="typeof option === 'object' ? option.value : option" />
        </el-select>

        <!-- 图片上传 -->
        <el-upload v-else-if="field.type === 'image'" class="image-uploader" action="#" :auto-upload="false"
          accept="image/*" :on-change="(file) => handleImageChange(file, field)" :show-file-list="false" :limit="1">
          <img v-if="field.imageUrl" :src="field.imageUrl" class="upload-image" />
          <div v-else class="upload-placeholder">
            <el-icon>
              <Plus />
            </el-icon>
            <span>上传图片</span>
          </div>
          <template #tip>
            <div class="el-upload__tip">{{ field.placeholder }}</div>
          </template>
        </el-upload>
      </el-form-item>
    </el-form>

    <el-button type="primary" class="generate-btn" @click="generateReport" :loading="isGenerating">
      {{ confirmButtonText }}
    </el-button>
  </div>
</template>

<script setup>
  import { ref, computed, watch, onBeforeUnmount, reactive } from 'vue'
  import { useChatStore } from '~/stores/chat'
  import { ElMessage } from 'element-plus'
  import { postOssSign } from '../../service/yapi'
  import { Plus, Close, DocumentCopy } from '@element-plus/icons-vue'

  const chatStore = useChatStore()
  const formRef = ref(null)
  const formData = reactive({})

  const props = defineProps({
    placeholder: {
      type: String,
      default: '输入消息...'
    },
    apiHeaders: {
      type: Object,
      default: () => ({})
    },
    appDetail: {
      type: Object,
      default: () => ({
        appConfig: "{}",
        welcomeTip: "",
        poster: ""
      })
    }
  })

  // 表单相关状态
  const formFields = ref([])
  const formSubmitted = ref(false)
  const confirmButtonText = ref('一键生成')  // 默认值
  const isGenerating = computed(() => chatStore.isGenerating)
  const isImageFile = (fileName) => {
    if (!fileName) return false;
    const extension = fileName.split('.').pop().toLowerCase();
    const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'svg'];
    return imageExtensions.includes(extension);
  };
  // 语音录制相关
  const isRecording = ref(false)
  const currentRecordingField = ref(null)
  const recordingTime = ref(0)
  const mediaRecorder = ref(null)
  const audioChunks = ref([])
  let recordingTimer = null

  // 初始化表单字段值
  const initializeFieldValue = (field) => {
    // 为文件类型添加额外属性
    if (field.type === 'file') {
      field.showUrlInput = false;
      field.urlInput = '';
      field.fileUrl = '';
    }

    switch (field.type) {
      case 'checkbox':
        return [];
      case 'range':
        return field.defaultValue || field.min || 0;
      case 'date':
      case 'text':
      case 'textarea':
      case 'selector':
      case 'image':
      case 'file':
      case 'color':
      case 'voice':
      case 'radio':
        return '';
      default:
        return '';
    }
  }

  // 解析 appConfig 并设置表单字段
  watch(() => props.appDetail.appConfig, (newConfig) => {
    try {
      const config = JSON.parse(newConfig || '{}')
      if (config && config.confirmText) {
        confirmButtonText.value = config.confirmText + `(${props.appDetail.cost}积分)`
      } else {
        confirmButtonText.value = confirmButtonText.value + `(${props.appDetail.cost}积分)`

      }

      if (config && config.form && Array.isArray(config.form.fields)) {
        formFields.value = config.form.fields.map(field => ({
          ...field,
          value: initializeFieldValue(field),
          fileName: '',
          imageUrl: '',
          recordingUrl: '',
        }))
      } else {
        formFields.value = []
      }
    } catch (error) {
      console.error('解析 appConfig 失败:', error)
      formFields.value = []
    }
  }, { immediate: true, deep: true })

  // 检查字段是否有值
  const hasValue = (field) => {
    if (field.type === 'checkbox') {
      return Array.isArray(field.value) && field.value.length > 0;
    }
    return field.value !== '' && field.value !== null && field.value !== undefined;
  }

  // 验证字段是否有效
  const isFieldValid = (field) => {
    if (field.required && !hasValue(field)) {
      return false;
    }

    if (field.minLength && field.value && field.value.length < field.minLength) {
      return false;
    }

    if (field.maxLength && field.value && field.value.length > field.maxLength) {
      return false;
    }

    return true;
  }

  // 获取错误消息
  const getErrorMessage = (field) => {
    if (field.required && !hasValue(field)) {
      return `${field.name}不能为空`
    }

    if (field.minLength && field.value && field.value.length < field.minLength) {
      return `${field.name}长度不能小于${field.minLength}`
    }

    if (field.maxLength && field.value && field.value.length > field.maxLength) {
      return `${field.name}长度不能超过${field.maxLength}`
    }

    return ''
  }

  // 处理文件选择变更
  const handleFileChange = (file, field) => {
    if (file.status === 'ready') {
      field.fileName = file.name;
    }
  }

  // 处理图片选择变更
  const handleImageChange = (file, field) => {
    field.value = file.raw

    // 创建预览
    const reader = new FileReader()
    reader.onload = (event) => {
      field.imageUrl = event.target.result
    }
    reader.readAsDataURL(file.raw)
  }

  // 语音录制功能
  const toggleVoiceRecording = async (field) => {
    if (isRecording.value) {
      stopRecording();
    } else {
      try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
        startRecording(stream, field);
      } catch (err) {
        console.error('无法访问麦克风:', err);
        alert('无法访问麦克风，请确保您已授予权限。');
      }
    }
  }

  const startRecording = (stream, field) => {
    audioChunks.value = [];
    mediaRecorder.value = new MediaRecorder(stream);

    mediaRecorder.value.ondataavailable = (e) => {
      if (e.data.size > 0) {
        audioChunks.value.push(e.data);
      }
    };

    mediaRecorder.value.onstop = () => {
      const audioBlob = new Blob(audioChunks.value, { type: 'audio/wav' });
      const audioUrl = URL.createObjectURL(audioBlob);

      if (currentRecordingField.value) {
        currentRecordingField.value.value = audioBlob;
        currentRecordingField.value.recordingUrl = audioUrl;
      }

      // 释放媒体流
      mediaRecorder.value.stream.getTracks().forEach(track => track.stop());
    };

    recordingTime.value = 0;
    recordingTimer = setInterval(() => {
      recordingTime.value++;

      // 如果超过最大录制时间，自动停止
      if (field.maxDuration && recordingTime.value >= field.maxDuration) {
        stopRecording();
      }
    }, 1000);

    currentRecordingField.value = field;
    isRecording.value = true;
    mediaRecorder.value.start();
  }

  const stopRecording = () => {
    if (mediaRecorder.value && mediaRecorder.value.state !== 'inactive') {
      mediaRecorder.value.stop();
    }

    if (recordingTimer) {
      clearInterval(recordingTimer);
      recordingTimer = null;
    }

    isRecording.value = false;
  }

  // 在组件销毁前停止录音
  onBeforeUnmount(() => {
    if (isRecording.value) {
      stopRecording();
    }
  });

  // 准备字段值，根据不同字段类型进行处理
  const prepareFieldValue = (field) => {
    // 特殊类型的字段处理
    switch (field.type) {
      case 'file':
        // 对于文件，返回规定的图片对象格式
        if (field.fileUrl) {
          return {
            type: "image",
            transfer_method: "remote_url",
            url: field.fileUrl + '?x-oss-process=image/resize,w_400',
            remote_url: field.fileUrl + '?x-oss-process=image/resize,w_400',
          };
        }
        return '';

      case 'radio':
        // 直接返回选中的值
        return field.value || '';

      case 'checkbox':
        // 对于复选框，返回选中值的数组或转为字符串
        return Array.isArray(field.value) ? field.value.join('、') : field.value;

      case 'selector':
        // 对于选择器，直接返回选中的值
        return field.value || '';

      case 'image':
        // 对于图片，可以返回预览URL或标识符
        return field.imageUrl || '';

      case 'voice':
        // 对于语音，返回录音URL或标识符
        return field.recordingUrl || '';

      case 'date':
        // 格式化日期
        if (field.value) {
          // 如果是Date对象，转换为字符串格式
          if (field.value instanceof Date) {
            return field.value.toISOString().split('T')[0];
          }
          return field.value;
        }
        return '';

      default:
        // 对于其他类型，直接返回值
        return field.value;
    }
  }

  // 生成报告 - 表单提交
  const generateReport = async () => {
    formSubmitted.value = true;

    // 1. 校验所有必填字段
    const invalidFields = formFields.value.filter(field => !isFieldValid(field));

    if (invalidFields.length > 0) {
      // 找到第一个错误字段并显示错误信息
      const firstError = invalidFields[0];
      ElMessage({
        message: getErrorMessage(firstError) || `${firstError.name}填写有误`,
        type: 'error',
        duration: 3000
      });

      // 滚动到错误字段
      if (formRef.value) {
        formRef.value.scrollToField(`${firstError.prop || firstError.name}`);
      }
      return;
    }

    // 2. 对特殊字段进行额外类型校验
    for (const field of formFields.value) {
      // 日期类型校验
      if (field.type === 'date' && field.value && !(field.value instanceof Date) && isNaN(new Date(field.value))) {
        ElMessage.error(`${field.name}的日期格式无效`);
        return;
      }

      // 数值范围校验
      if (field.type === 'range') {
        const numValue = Number(field.value);
        if (isNaN(numValue) || numValue < field.min || numValue > field.max) {
          ElMessage.error(`${field.name}的值必须在 ${field.min} 到 ${field.max} 之间`);
          return;
        }
      }

      // 复选框至少选择一项校验(如果必填)
      if (field.type === 'checkbox' && field.required && (!Array.isArray(field.value) || field.value.length === 0)) {
        ElMessage.error(`请至少选择一个${field.name}`);
        return;
      }
    }

    // 3. 构建数据对象
    const inputs = {};

    formFields.value.forEach(field => {
      inputs[field.prop || field.name] = prepareFieldValue(field);
    });
    // 将inputs中 属性值为空的属性删除
    for (const key in inputs) {
      if (inputs[key] === '' || inputs[key] === null || inputs[key] === undefined) {
        delete inputs[key];
      }
    }
    try {
      // 4. 解析配置获取查询文本
      const config = JSON.parse(props.appDetail.appConfig || '{}');
      const queryText = config.form?.query || "生成";

      // 5. 更新对话输入数据
      chatStore.updateConversationInputs(inputs);

      // 6. 发送消息
      await chatStore.sendMessage({
        text: queryText,
        inputs // 传递结构化表单数据
      }, props.apiHeaders);

    } catch (error) {
      console.error('发送表单数据时出错:', error);
      ElMessage.error('提交表单失败，请稍后重试');
    }
  }

  // 填充示例数据
  const fillExamples = () => {
    formFields.value.forEach(field => {
      if (field.example !== undefined) {
        if (field.type === 'checkbox' && typeof field.example === 'string') {
          // 处理复选框示例值，将字符串转换为数组
          const exampleValues = field.example.split('、');
          field.value = field.options
            .filter(option => exampleValues.includes(option.label) || exampleValues.includes(option.value))
            .map(option => option.value);
        } else if (field.type === 'selector') {
          // 处理选择器示例值
          if (Array.isArray(field.options)) {
            // 如果options是简单数组(字符串数组)
            if (typeof field.options[0] === 'string') {
              field.value = field.example;
            } else {
              // 如果options是对象数组
              const option = field.options.find(opt =>
                opt.label === field.example || opt.value === field.example
              );
              field.value = option ? option.value : field.example;
            }
          }
        } else {
          field.value = field.example;
        }
      }
    });

    ElMessage({
      message: '已填入示例数据',
      type: 'success',
      duration: 2000
    });
  };

  // OSS上传相关
  const uploadUrl = ref('');
  const uploadHeaders = ref({});
  const uploadData = ref({
    key: '',
    policy: '',
    OSSAccessKeyId: '',
    success_action_status: '200',
    signature: '',
  });

  // 获取OSS上传凭证
  const getOssSignature = async (file, field) => {
    try {
      // 这里需要您实际的API调用，类似于[id].vue中的postOssSign
      let data = await postOssSign({})


      if (data && data.data) {
        uploadUrl.value = data.data.host;
        uploadData.value = {
          key: `dify/apps/${props.appDetail.id}/uploads/${generateRandomFileName(file)}`,
          policy: data.data.policy,
          OSSAccessKeyId: data.data.OSSAccessKeyId,
          success_action_status: '200',
          signature: data.data.signature,
        };
        return true;
      }
      return false;
    } catch (error) {
      console.error('获取OSS签名失败', error);
      ElMessage.error('获取上传凭证失败');
      return false;
    }
  };

  // 生成随机文件名
  const generateRandomFileName = (file) => {
    const extension = file.name.split('.').pop();
    return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}.${extension}`;
  };

  // 文件上传前处理
  const beforeFileUpload = async (file, field) => {
    // 文件类型检查
    if (field.accept && !file.type.match(field.accept.replace(/\./g, '').replace(/,/g, '|'))) {
      ElMessage.error(`只能上传${field.accept}类型的文件`);
      return false;
    }

    // 文件大小限制，默认10MB
    const maxSize = field.maxSize || 10;
    if (file.size / 1024 / 1024 > maxSize) {
      ElMessage.error(`文件大小不能超过${maxSize}MB`);
      return false;
    }

    // 获取OSS签名
    return await getOssSignature(file, field);
  };

  // 文件上传成功处理
  const handleFileSuccess = (response, file, field) => {
    console.log("%c Line:616 🍕 field", "color:#ffdd4d", field, uploadData.value);
    const baseUrl = 'https://xiaobao2.oss-cn-beijing.aliyuncs.com/'; // 替换为您的OSS域名
    field.value = `${baseUrl}${uploadData.value.key}`;
    field.fileUrl = field.value;
    field.fileName = file.name;
  };

  // URL输入相关
  const toggleUrlInput = (field) => {
    field.showUrlInput = !field.showUrlInput;
    if (!field.urlInput) {
      field.urlInput = '';
    }
  };

  // 确认URL输入
  const confirmUrlInput = (field) => {
    if (!field.urlInput || !isValidUrl(field.urlInput)) {
      ElMessage.warning('请输入有效的URL');
      return;
    }

    field.value = field.urlInput;
    field.fileUrl = field.urlInput;
    field.fileName = getFileNameFromUrl(field.urlInput);
    field.showUrlInput = false;
  };

  // 检查URL是否有效
  const isValidUrl = (url) => {
    try {
      new URL(url);
      return true;
    } catch (e) {
      return false;
    }
  };

  // 从URL中获取文件名
  const getFileNameFromUrl = (url) => {
    try {
      const urlObj = new URL(url);
      const pathname = urlObj.pathname;
      return pathname.substring(pathname.lastIndexOf('/') + 1);
    } catch (e) {
      return '未知文件';
    }
  };

  // 移除文件
  const removeFile = (field) => {
    field.value = '';
    field.fileUrl = '';
    field.fileName = '';
    field.urlInput = '';

    // 显示移除成功的消息提示
    ElMessage({
      message: '文件已删除',
      type: 'success',
      duration: 2000
    });
  };
</script>

<style lang="scss" scoped>

  /* 表单容器样式 */
  .form-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
    width: 100%;
    position: relative;
  }

  /* 表单头部样式 */
  /* 表单头部样式 */
  .form-header {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 15px;
  }

  .fill-examples-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 15px;
    font-weight: 600;
    padding: 18px 20px;
    border-radius: 8px;
    background: linear-gradient(135deg, #35c6f4, #3a99e8);
    border: none;
    color: white;
    box-shadow: 0 4px 12px rgba(53, 198, 244, 0.35);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;

    &::after {
      content: "";
      position: absolute;
      top: -50%;
      left: -50%;
      width: 200%;
      height: 200%;
      background: radial-gradient(circle, rgba(255, 255, 255, 0.3) 0%, transparent 70%);
      opacity: 0;
      transition: opacity 0.4s ease;
    }

    &:hover {
      background: linear-gradient(135deg, #28b8e8, #2d8ad6);
      transform: translateY(-3px);
      box-shadow: 0 6px 15px rgba(53, 198, 244, 0.45);

      &::after {
        opacity: 1;
        animation: ripple 1s ease-out;
      }
    }

    &:active {
      transform: translateY(-1px);
      box-shadow: 0 3px 8px rgba(53, 198, 244, 0.4);
    }

    :deep(.el-icon) {
      font-size: 18px;
      animation: float 2s infinite alternate ease-in-out;
      margin-right: 2px;
    }

    @keyframes float {
      0% {
        transform: translateY(0) rotate(0deg);
      }

      50% {
        transform: translateY(-3px) rotate(5deg);
      }

      100% {
        transform: translateY(0) rotate(0deg);
      }
    }

    @keyframes ripple {
      0% {
        transform: scale(0.5);
        opacity: 0.5;
      }

      100% {
        transform: scale(1);
        opacity: 0;
      }
    }
  }

  /* 紧凑表单样式 - 修改为单行展示 */
  .compact-form {
    display: flex;
    flex-direction: column;
    gap: 10px;

    :deep(.el-form-item) {
      margin-bottom: 0;
      padding: 12px;
      background-color: #f9f9fa;
      border-radius: 8px;
      transition: all 0.2s ease;
      margin-right: 0;
      width: 100%;
      display: flex;
      flex-direction: column;
      align-items: flex-start; // 修改为flex-start使其左对齐
      justify-content: flex-start;

      &:hover {
        background-color: #f2f2f3;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
      }

      &.is-error {
        background-color: #fff2f0;
        border-left: 3px solid #ff4d4f;
      }
    }

    :deep(.el-form-item__label) {
      padding-bottom: 8px;
      font-weight: 500;
      font-size: 14px;
      line-height: 1.2;
      color: #333;
      width: 100%;
      text-align: left;

      &::before {
        content: "";
        margin-right: 4px;
      }

      /* 必填项标记 */
      .el-form-item.is-required & {
        &::before {
          content: "*";
          color: #f56c6c;
          margin-right: 4px;
        }
      }
    }

    :deep(.el-form-item__content) {
      width: 100%;
      max-width: 500px;
      margin-left: 0;
      display: flex;
      flex-direction: column;
      align-items: flex-start; // 修改为flex-start使其左对齐
      justify-content: flex-start;
    }

    :deep(.el-form-item__error) {
      padding-top: 4px;
      font-size: 12px;
      position: absolute;
      left: 100px;
      top: -35px;
      text-align: center;
    }

    :deep(.el-input__wrapper),
    :deep(.el-textarea__wrapper),
    :deep(.el-select .el-input__wrapper),
    :deep(.el-date-editor.el-input__wrapper) {
      border-radius: 6px;
      box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1) inset;
      padding: 0 12px;
      width: 100%;

      &:hover,
      &:focus {
        box-shadow: 0 0 0 1px #409EFF inset;
      }

      &::placeholder {
        color: #aaa;
        font-style: italic;
        opacity: 0.8;
      }
    }

    /* 优化textarea样式 */
    :deep(.el-textarea__wrapper) {
      padding: 8px 12px;
    }

    /* 优化placeholder的显示 */
    :deep(.el-input__placeholder) {
      transition: all 0.25s;
      transform-origin: left;
      color: #909399;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }

    :deep(.el-input__inner:focus + .el-input__placeholder) {
      opacity: 0.7;
      transform: translateY(-2px) scale(0.85);
    }

    :deep(.el-radio-group) {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      justify-content: center;
      width: 100%;
    }

    :deep(.el-radio) {
      margin-right: 0;
      padding: 6px 10px;
      background-color: #fff;
      border-radius: 6px;
      transition: all 0.2s ease;

      &:hover {
        background-color: #f0f9ff;
      }

      &.is-checked {
        background-color: #e6f7ff;
      }
    }

    :deep(.el-checkbox-group) {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
      justify-content: center;
      width: 100%;
    }

    :deep(.el-checkbox) {
      margin-right: 0;
      padding: 6px 10px;
      background-color: #fff;
      border-radius: 6px;
      transition: all 0.2s ease;

      &:hover {
        background-color: #f0f9ff;
      }

      &.is-checked {
        background-color: #e6f7ff;
      }
    }

    /* 上传组件优化 */
    :deep(.el-upload) {
      display: block;
      width: 100%;

      .el-button {
        margin-bottom: 8px;
        width: 100%;
        justify-content: center;
      }

      .el-upload__tip {
        color: #909399;
        font-size: 12px;
        line-height: 1.4;
      }
    }
  }

  /* 根据视口大小调整网格布局 */
  @media (max-width: 768px) {
    .compact-form {
      :deep(.el-form-item__content) {
        max-width: 100%;
      }
    }
  }

  .color-field {
    display: flex;
    align-items: center;
    gap: 10px;

    .color-value {
      font-size: 14px;
    }
  }

  .voice-field {
    display: flex;
    flex-direction: column;
    gap: 8px;

    .voice-preview {
      margin-top: 8px;
      width: 100%;

      audio {
        width: 100%;
      }
    }
  }

  .file-preview {
    margin-top: 12px;
    padding: 10px;
    background-color: #f5f7fa;
    border-radius: 6px;

    .file-url {
      font-size: 13px;
      color: #606266;
      word-break: break-all;
      margin-bottom: 8px;
    }

    .image-preview {
      margin-top: 10px;

      img {
        max-width: 100%;
        max-height: 200px;
        border-radius: 4px;
        border: 1px solid #ebeef5;
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
      }
    }
  }

  /* 统一按钮样式 */
  .file-upload-wrapper {
    .upload-buttons {
      display: flex;
      gap: 10px;
      margin-bottom: 10px;

      .upload-field,
      .url-button {
        flex: 1;
      }

      :deep(.el-upload) {
        display: block;
        width: 100%;

        .el-button {
          width: 100%;
          justify-content: center;
        }
      }
    }

    .url-input-section {
      margin-bottom: 10px;
    }

    .file-preview {
      margin-top: 12px;
      padding: 10px;
      background-color: #f5f7fa;
      border-radius: 6px;

      .image-preview-container {
        position: relative;
        width: 60px;
        margin: 0 auto;

        .delete-button {
          position: absolute;
          top: -10px;
          right: -10px;
          width: 24px;
          height: 24px;
          border-radius: 50%;
          background-color: #f56c6c;
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          z-index: 10;
          box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);

          &:hover {
            background-color: #e64242;
          }
        }

        .image-preview {
          width: 60px;
          height: 60px;
          overflow: hidden;
          border-radius: 4px;
          border: 1px solid #ebeef5;
          box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

          img {
            width: 100%;
            height: 100%;
            object-fit: cover;
            /* 保持图片比例并充满容器 */
            display: block;
          }
        }

        .file-name {
          margin-top: 8px;
          font-size: 13px;
          color: #606266;
          text-align: center;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 200px;
        }
      }

      .file-info {
        .file-name {
          font-weight: bold;
          margin-bottom: 5px;
        }

        .file-url {
          font-size: 13px;
          color: #606266;
          word-break: break-all;
          margin-bottom: 10px;
          background-color: #ebeef5;
          padding: 5px 8px;
          border-radius: 4px;
        }
      }
    }
  }

  .image-uploader {
    :deep(.el-upload) {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.3s;

      &:hover {
        border-color: #409EFF;
      }
    }

    .upload-image {
      width: 100%;
      height: 100px;
      object-fit: cover;
      display: block;
    }

    .upload-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 100px;
      color: #8c939d;
    }
  }

  .generate-btn {
    width: 100%;
    margin-top: 8px;
    font-size: 16px;
    padding: 12px;
    background: linear-gradient(270deg, #4bb3a3 0%, #86dd98 99%);
    border: none;

    &:hover,
    &:focus {
      background: linear-gradient(270deg, #40a395 0%, #76cd88 99%);
      opacity: 0.9;
    }
  }

  /* 优化选择器样式 */
  :deep(.el-select) {
    width: 100%;

    .el-input {
      width: 100%;
    }
  }

  /* 复选框样式优化 */
  :deep(.el-checkbox-group) {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    justify-content: center;
    width: 100%;

    .el-checkbox {
      margin-right: 0;
      margin-left: 0;
    }
  }
</style>
